<template>
  <div class="page-container">
    <!-- Main Content -->
    <div class="main-content">
      <!-- Query Conditions -->
      <el-card shadow="hover" style="margin-bottom: 20px;">
        <template #header>
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <span style="font-size: 16px; font-weight: 600;">Query Conditions</span>
            <el-button @click="handleReset" size="small">Reset Conditions</el-button>
          </div>
        </template>

        <el-form
          ref="queryFormRef"
          :model="queryForm"
          :inline="true"
          label-width="100px"
        >
          <el-form-item label="Order ID">
            <el-input
              v-model="queryForm.orderId"
              placeholder="Please enter order ID"
              clearable
              style="width: 200px;"
            />
          </el-form-item>


          <el-form-item label="User UID">
            <el-input
              v-model="queryForm.uid"
              placeholder="Please enter user UID"
              clearable
              style="width: 200px;"
            />
          </el-form-item>

          <el-form-item label="Order Status">
            <el-select
              v-model="queryForm.status"
              placeholder="Please select order status"
              clearable
              style="width: 180px;"
            >
              <el-option
                v-for="status in payoutStatusOptions"
                :key="status.value"
                :label="status.label"
                :value="status.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="Customer Service">
            <el-input
              v-model="queryForm.createdByName"
              placeholder="Please enter customer service name"
              clearable
              style="width: 200px;"
            />
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="handleSearch"
              :loading="isLoading"
              style="margin-left: 10px;"
            >
              <el-icon class="el-icon--left"><Search /></el-icon>
              Query
            </el-button>
            <el-button @click="handleReset">Reset</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- Order List -->
      <el-card shadow="hover">
        <template #header>
          <div style="display: flex; align-items: center; justify-content: space-between;">
            <span style="font-size: 16px; font-weight: 600;">Payment Order List</span>
            <div>
              <el-button
                type="primary"
                size="small"
                @click="$router.push('/payout/create')"
              >
                <el-icon class="el-icon--left"><Plus /></el-icon>
                New Order
              </el-button>
              <el-button
                size="small"
                @click="handleRefresh"
                :loading="isLoading"
              >
                <el-icon class="el-icon--left"><Refresh /></el-icon>
                Refresh
              </el-button>
            </div>
          </div>
        </template>

        <!-- Data Table -->
        <el-table
          v-loading="isLoading"
          :data="orderList"
          style="width: 100%;"
          stripe
          size="default"
        >
          <el-table-column prop="orderId" label="Order ID" width="200" show-overflow-tooltip />
          
          <el-table-column prop="uid" label="User UID" width="120" />
          
          <el-table-column prop="amount" label="Payment Amount" width="120" align="right">
            <template #default="scope">
              <span style="color: #f56c6c; font-weight: 600;">
                {{ formatCurrency(scope.row.amount) }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="Order Status" width="130">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)" size="small">
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="paymentChannel" label="Payment Channel" width="100">
            <template #default="scope">
              <el-tag size="small" type="info">
                {{ getChannelDisplayName(scope.row.paymentChannel) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="receiverName" label="Receiver" width="120" show-overflow-tooltip />
          
          <el-table-column prop="createdByName" label="Customer Service" width="120" show-overflow-tooltip />

          <el-table-column prop="createdAt" label="Created Time" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.createdAt) }}
            </template>
          </el-table-column>

          <el-table-column label="Actions" width="200" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                type="primary"
                link
                @click="handleViewDetail(scope.row)"
              >
                Details
              </el-button>

              <el-button
                v-if="canConfirm(scope.row)"
                size="small"
                type="success"
                link
                @click="handleConfirm(scope.row)"
              >
                Confirm
              </el-button>

              <el-button
                v-if="canExecute(scope.row)"
                size="small"
                type="warning"
                link
                @click="handleExecute(scope.row)"
              >
                Execute
              </el-button>

              <el-button
                v-if="canCancel(scope.row)"
                size="small"
                type="danger"
                link
                @click="handleCancel(scope.row)"
              >
                Cancel
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- Pagination -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.page"
            v-model:page-size="pagination.limit"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- Order Detail Dialog -->
    <el-dialog
      v-model="detailDialogVisible"
      title="Payment Order Details"
      width="800px"
      :close-on-click-modal="false"
    >
      <div v-if="selectedOrder" class="order-detail">
        <el-descriptions :column="2" border size="default">
          <el-descriptions-item label="Order ID">
            {{ selectedOrder.orderId }}
          </el-descriptions-item>
          <el-descriptions-item label="Order Status">
            <el-tag :type="getStatusTagType(selectedOrder.status)">
              {{ getStatusText(selectedOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="User UID">
            {{ selectedOrder.uid }}
          </el-descriptions-item>
          <el-descriptions-item label="Payment Amount">
            <span style="color: #f56c6c; font-weight: 600;">
              {{ formatCurrency(selectedOrder.amount) }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item label="Payment Channel">
            {{ getChannelDisplayName(selectedOrder.paymentChannel) }}
          </el-descriptions-item>
          <el-descriptions-item label="Payment Method">
            {{ selectedOrder.paymentMethod === 'BankTransfer' ? 'Bank Transfer' : 'QR Code Payment' }}
          </el-descriptions-item>
          <el-descriptions-item label="Receiver Name">
            {{ selectedOrder.receiverName }}
          </el-descriptions-item>
          <el-descriptions-item label="Receiver Bank Card Number">
            {{ selectedOrder.receiverBankCard }}
          </el-descriptions-item>
          <el-descriptions-item label="Bank Code">
            {{ selectedOrder.bankCode || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="Customer Service">
            {{ selectedOrder.createdByName }}
          </el-descriptions-item>
          <el-descriptions-item label="Created Time">
            {{ formatDateTime(selectedOrder.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="Confirmed Time">
            {{ selectedOrder.confirmedAt ? formatDateTime(selectedOrder.confirmedAt) : '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="Confirmed By">
            {{ selectedOrder.confirmedByUser?.username || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="Platform Order Number">
            {{ selectedOrder.platOrderNum || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="Remark" :span="2">
            {{ selectedOrder.remark || '-' }}
          </el-descriptions-item>
        </el-descriptions>

        <!-- Payment Response Information -->
        <div v-if="selectedOrder.paymentResponse" class="payment-response-section" style="margin-top: 20px;">
          <el-divider content-position="left">Payment Response Details</el-divider>
          <el-alert
            v-if="selectedOrder.status === 'FAILED'"
            :title="getPaymentErrorMessage(selectedOrder.paymentResponse)"
            type="error"
            show-icon
            :closable="false"
            style="margin-bottom: 15px;"
          >
            <template #default>
              <div style="margin-top: 10px;">
                <strong>Error Code:</strong> {{ getPaymentErrorCode(selectedOrder.paymentResponse) }}<br/>
                <strong>Details:</strong> {{ getPaymentErrorDetails(selectedOrder.paymentResponse) }}
              </div>
            </template>
          </el-alert>
          
          <el-collapse>
            <el-collapse-item title="View Complete Response Data" name="response">
              <pre style="background: #f5f5f5; padding: 15px; border-radius: 4px; overflow: auto; max-height: 300px;">{{ formatPaymentResponse(selectedOrder.paymentResponse) }}</pre>
            </el-collapse-item>
          </el-collapse>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">Close</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Confirm Payment Dialog -->
    <el-dialog
      v-model="confirmDialogVisible"
      title="Confirm Payment Order"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="confirm-content">
        <el-alert
          title="Please enter payment password to confirm this payment order"
          type="warning"
          show-icon
          :closable="false"
          style="margin-bottom: 20px;"
        />

        <el-form ref="confirmFormRef" :model="confirmForm" :rules="confirmRules" label-width="100px">
          <el-form-item label="Payment Password" prop="payoutPassword">
            <el-input
              v-model="confirmForm.payoutPassword"
              type="password"
              placeholder="Please enter payment password"
              show-password
              maxlength="50"
            />
          </el-form-item>
        </el-form>

        <div style="margin-top: 20px; padding: 16px; background-color: #fafafa; border-radius: 4px;">
          <p style="margin: 0; color: #666; font-size: 14px;">
            <strong>Order Information:</strong><br>
            Order ID: {{ pendingConfirmOrder?.orderId }}<br>
            Payment Amount: {{ pendingConfirmOrder ? formatCurrency(pendingConfirmOrder.amount) : '' }}<br>
            Receiver: {{ pendingConfirmOrder?.receiverName }}
          </p>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">Cancel</el-button>
          <el-button
            type="primary"
            @click="handleConfirmSubmit"
            :loading="isConfirming"
          >
            Confirm Payment
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { trpc } from '../utils/trpc'
import { formatDateTime, formatCurrency } from '../utils/common'

// Reactive data
const queryFormRef = ref<FormInstance>()
const confirmFormRef = ref<FormInstance>()
const isLoading = ref(false)
const isConfirming = ref(false)
const orderList = ref<any[]>([])
const detailDialogVisible = ref(false)
const confirmDialogVisible = ref(false)
const selectedOrder = ref<any>(null)
const pendingConfirmOrder = ref<any>(null)

// Form data
const queryForm = reactive({
  orderId: '',
  uid: '',
  status: '',
  createdByName: '',
})

const confirmForm = reactive({
  payoutPassword: ''
})

// Pagination data
const pagination = reactive({
  page: 1,
  limit: 20,
  total: 0,
})

// Payment status options
const payoutStatusOptions = [
  { label: 'Pending', value: 'PENDING' },
  { label: 'Pending Confirm', value: 'PENDING_CONFIRM' },
  { label: 'Confirmed', value: 'CONFIRMED' },
  { label: 'Processing', value: 'PROCESSING' },
  { label: 'Completed', value: 'COMPLETED' },
  { label: 'Failed', value: 'FAILED' },
  { label: 'Cancelled', value: 'CANCELLED' },
]

// Confirm form validation rules
const confirmRules: FormRules = {
  payoutPassword: [
    { required: true, message: 'Please enter payment password', trigger: 'blur' },
    { min: 6, max: 50, message: 'Payment password length should be 6-50 characters', trigger: 'blur' }
  ]
}

// Methods
const getStatusText = (status: string) => {
  const option = payoutStatusOptions.find(item => item.value === status)
  return option?.label || status
}

const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    PENDING: 'info',
    PENDING_CONFIRM: 'warning',
    CONFIRMED: 'success',
    PROCESSING: 'warning',
    COMPLETED: 'success',
    FAILED: 'danger',
    CANCELLED: 'info'
  }
  return typeMap[status] || 'info'
}

const canConfirm = (order: any) => {
  return order.status === 'PENDING_CONFIRM'
}

const canExecute = (order: any) => {
  return order.status === 'CONFIRMED'
}

const canCancel = (order: any) => {
  return ['PENDING_CONFIRM', 'CONFIRMED'].includes(order.status)
}

// Methods for handling payment response information
const getPaymentErrorMessage = (paymentResponse: string) => {
  try {
    const response = JSON.parse(paymentResponse)
    // Support error message formats for 668Pay and TopPay
    return response.errorMessage || response.platRespMessage || response.msg || 'Payment failed'
  } catch {
    return 'Failed to parse payment response'
  }
}

const getPaymentErrorCode = (paymentResponse: string) => {
  try {
    const response = JSON.parse(paymentResponse)
    // Support error code formats for 668Pay and TopPay
    return response.errorCode || response.platRespCode || response.code?.toString() || 'Unknown error code'
  } catch {
    return 'JSON_PARSE_ERROR'
  }
}

const getPaymentErrorDetails = (paymentResponse: string) => {
  try {
    const response = JSON.parse(paymentResponse)
    const details = []
    
    // TopPay format
    if (response.platOrderNum) {
      details.push(`Platform Order Number: ${response.platOrderNum}`)
    }
    
    if (response.orderNum) {
      details.push(`Merchant Order Number: ${response.orderNum}`)
    }
    
    // 668Pay format
    if (response.data?.transferId) {
      details.push(`Transfer Order Number: ${response.data.transferId}`)
    }
    
    if (response.data?.mchOrderNo) {
      details.push(`Merchant Order Number: ${response.data.mchOrderNo}`)
    }
    
    if (response.data?.state !== undefined) {
      const stateText = response.data.state === 3 ? 'Transfer Failed' : `State Code: ${response.data.state}`
      details.push(`Transfer Status: ${stateText}`)
    }
    
    if (response.status !== undefined) {
      details.push(`Payment Status: ${response.status}`)
    }
    
    if (response.statusMsg) {
      details.push(`Status Message: ${response.statusMsg}`)
    }
    
    return details.length > 0 ? details.join(', ') : 'No detailed information'
  } catch {
    return 'Unable to parse response details'
  }
}

const formatPaymentResponse = (paymentResponse: string) => {
  try {
    const response = JSON.parse(paymentResponse)
    return JSON.stringify(response, null, 2)
  } catch {
    return paymentResponse
  }
}

const getChannelDisplayName = (channel: string) => {
  switch (channel) {
    case 'TOPPAY':
      return 'TopPay'
    case 'PAY668':
      return '668Pay'
    case 'LSPPAY':
      return 'LSPPAY'
    default:
      return channel
  }
}

const handleSearch = async () => {
  pagination.page = 1
  await loadOrderList()
}

const handleReset = () => {
  queryFormRef.value?.resetFields()
  Object.assign(queryForm, {
    orderId: '',
    uid: '',
    status: '',
    createdByName: '',
  })
  handleSearch()
}

const handleRefresh = () => {
  loadOrderList()
}

const handleSizeChange = (newSize: number) => {
  pagination.limit = newSize
  pagination.page = 1
  loadOrderList()
}

const handleCurrentChange = (newPage: number) => {
  pagination.page = newPage
  loadOrderList()
}

const handleViewDetail = async (order: any) => {
  try {
    const result = await trpc.payout.getByOrderId.query({ orderId: order.orderId })
    if (result.success) {
      selectedOrder.value = result.data
      detailDialogVisible.value = true
    } else {
      ElMessage.error(result.message || 'Failed to get order details')
    }
  } catch (error: any) {
    console.error('Get order detail error:', error)
    ElMessage.error(error.message || 'Failed to get order details')
  }
}

const handleConfirm = (order: any) => {
  pendingConfirmOrder.value = order
  confirmForm.payoutPassword = ''
  confirmDialogVisible.value = true
}

const handleConfirmSubmit = async () => {
  if (!confirmFormRef.value) return

  const valid = await confirmFormRef.value.validate().catch(() => false)
  if (!valid) return

  isConfirming.value = true

  try {
    const result = await trpc.payout.confirm.mutate({
      orderId: pendingConfirmOrder.value.orderId,
      payoutPassword: confirmForm.payoutPassword
    })

    if (result.success) {
      ElMessage.success('Payment order confirmed successfully!')
      confirmDialogVisible.value = false
      await loadOrderList()
    } else {
      ElMessage.error(result.message || 'Failed to confirm payment order')
    }
  } catch (error: any) {
    console.error('Confirm payout order error:', error)
    ElMessage.error(error.message || 'Failed to confirm payment order')
  } finally {
    isConfirming.value = false
  }
}

const handleExecute = async (order: any) => {
  const confirmed = await ElMessageBox.confirm(
    `Confirm to execute payment order ${order.orderId}? After execution, the payment interface will be called for actual payment.`,
    'Confirm Execution',
    {
      confirmButtonText: 'Confirm Execution',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  ).catch(() => false)

  if (!confirmed) return

  try {
    const result = await trpc.payout.execute.mutate({ orderId: order.orderId })
    
    if (result.success) {
      if (result.data.success) {
        ElMessage.success('Payment executed successfully!')
      } else {
        ElMessage.warning(`Payment execution failed: ${result.data.errorMessage}`)
      }
      await loadOrderList()
    } else {
      ElMessage.error(result.message || 'Failed to execute payment')
    }
  } catch (error: any) {
    console.error('Execute payout order error:', error)
    ElMessage.error(error.message || 'Failed to execute payment')
  }
}

const handleCancel = async (order: any) => {
  const confirmed = await ElMessageBox.confirm(
    `Confirm to cancel payment order ${order.orderId}? After cancellation, the order cannot be processed further.`,
    'Confirm Cancellation',
    {
      confirmButtonText: 'Confirm Cancellation',
      cancelButtonText: 'Go Back',
      type: 'warning',
    }
  ).catch(() => false)

  if (!confirmed) return

  try {
    const result = await trpc.payout.cancel.mutate({ orderId: order.orderId })
    
    if (result.success) {
      ElMessage.success('Payment order cancelled successfully!')
      await loadOrderList()
    } else {
      ElMessage.error(result.message || 'Failed to cancel payment order')
    }
  } catch (error: any) {
    console.error('Cancel payout order error:', error)
    ElMessage.error(error.message || 'Failed to cancel payment order')
  }
}

const loadOrderList = async () => {
  isLoading.value = true
  
  try {
    const queryParams: any = {
      page: pagination.page,
      limit: pagination.limit,
    }

    // Add query conditions
    if (queryForm.orderId) queryParams.orderId = queryForm.orderId
    if (queryForm.uid) queryParams.uid = queryForm.uid
    if (queryForm.status) queryParams.status = queryForm.status
    if (queryForm.createdByName) queryParams.createdByName = queryForm.createdByName

    const result = await trpc.payout.query.query(queryParams)
    
    if (result.success) {
      orderList.value = result.data.records
      pagination.total = result.data.pagination.total
    } else {
      ElMessage.error(result.message || 'Failed to query payment orders')
      orderList.value = []
      pagination.total = 0
    }
  } catch (error: any) {
    console.error('Load payout orders error:', error)
    ElMessage.error(error.message || 'Failed to query payment orders')
    orderList.value = []
    pagination.total = 0
  } finally {
    isLoading.value = false
  }
}

// Lifecycle
onMounted(async () => {
  await loadOrderList()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.main-content {
  margin-top: 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.order-detail {
  margin: 20px 0;
}

.confirm-content {
  padding: 10px 0;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-card__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}
</style>